我们来观察以下四段代码的区别:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 1 setTimeout throw
const p1 = new Promise(function (resolve, reject) {
setTimeout(function () {
throw new Error("test");
}, 0);
});
p1.catch(function (error) {
console.log("Catch1: ", error);
});
// Uncaught Error: test

// 2 setTimeout reject
const p2 = new Promise(function (resolve, reject) {
setTimeout(function () {
reject(new Error("test"));
}, 0);
});
p2.catch(function (error) {
console.log("Catch2: ", error);
});
// Catch2: Error: test

// 3 throw
const p3 = new Promise(function (resolve, reject) {
throw new Error("test");
});
p3.catch(function (error) {
console.log("Catch3: ", error);
});
// Catch3: Error: test

// 4 reject
const p4 = new Promise(function (resolve, reject) {
reject(new Error("test"));
});
p4.catch(function (error) {
console.log("Catch4: ", error);
});
// Catch4: Error: test

thencatch返回新的Promise对象,finally返回本身。

allthencatch的调用优先级低于all的元素本身的thencatch

以下两者代码的区别:(定义 Promise 的时候会执行其中的代码)

1
2
3
4
5
6
7
8
9
10
11
const f = () => console.log("now");
Promise.resolve().then(f);
console.log("next");
// next
// now

const f = () => console.log("now");
(() => new Promise((resolve) => resolve(f())))();
console.log("next");
// now
// next